package tech.yangzhijie.basic.knowledge.other;

/**
 * CAS算法简单模拟
 */
public class CompareAndSwapTest {

    public static void main(String[] args) {
        final CompareAndSwap cas = new CompareAndSwap();

        for(int i = 0;i < 10;i++){
            new Thread(()->{
                int value = cas.getValue();
                boolean b = cas.compareAndSet(value, (int) (Math.random() * 11));
                System.out.println(b);
            }).start();
        }
    }
}

class CompareAndSwap {

    private int value = 1;

    public synchronized int getValue(){
        return this.value;
    }

    public synchronized int compareToSwap(int expectedValue,int newValue){
        int oldValue = this.value;
        if(oldValue == expectedValue){
            this.value = newValue;
        }
        return oldValue;
    }

    public synchronized boolean compareAndSet(int expectedValue,int newValue){
        return expectedValue == compareToSwap(expectedValue,newValue);
    }
}
